#!/usr/bin/env python
# -*-  coding: utf-8 -*-
#   
#   Copyright © 2008, 2009, 2010 Jan Svec <honza.svec@gmail.com> and Filip Jurcicek <filip.jurcicek@gmail.com>
#   
#   This file is part of Gmail Backup.
#
#   Gmail Backup is free software: you can redistribute it and/or modify it
#   under the terms of the GNU General Public License as published by the Free
#   Software Foundation, either version 3 of the License, or (at your option)
#   any later version.
#
#   Gmail Backup is distributed in the hope that it will be useful, but WITHOUT
#   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#   more details.
#
#   You should have received a copy of the GNU General Public License along
#   with Gmail Backup.  If not, see <http://www.gnu.org/licenses/
#
#   See LICENSE file for license details
#
#   With changes by Jesper Hertel <jesper.hertel@gmail.com> (JH).

import sys

from InterruptableThread import InterruptableThread
import gmb

_submoduleListForVersioning = [gmb]
import versioning; _revisionInfo = versioning.getRevisionInfoFromTagsAndSubModules('$Revision$', '$Date$', _submoduleListForVersioning)


class ThreadedGmailBackup(gmb.GmailBackup):

    def _runThread(self, method, *args, **kwargs):
        try:
            method(self, *args, **kwargs)
        except:
            exceptionType, exception, exceptionTraceback = sys.exc_info()
            self.notifier.notifyException(exceptionType, exception, exceptionTraceback)

    def _callMethodThreaded(self, method, args, kwargs):
        interruptableThreadObject = InterruptableThread(target=self._runThread, args= (method,) + args, kwargs=kwargs)
        interruptableThreadObject.start()
        return interruptableThreadObject
    
    def backup(self, *args, **kwargs):
        '''
        Run a backup process in a separate thread.
        
        Return an instance of an InterruptableThread class.
        '''
        method = gmb.GmailBackup.backup
        interruptableThreadObject = self._callMethodThreaded(method, args, kwargs)
        return interruptableThreadObject

    def restore(self, *args, **kwargs):
        '''
        Run a restore process in a separate thread.
        
        Return an instance of an InterruptableThread class.
        '''
        method = gmb.GmailBackup.restore
        interruptableThreadObject = self._callMethodThreaded(method, args, kwargs)
        return interruptableThreadObject

    def checkForNewVersion(self, *args, **kwargs):
        '''
        Run a check for new version process in a separate thread.
        
        Return an instance of an InterruptableThread class.
        '''
        method = gmb.GmailBackup.checkForNewVersion
        interruptableThreadObject = self._callMethodThreaded(method, args, kwargs)
        return interruptableThreadObject
